<template lang="pug">
  div
    h1 ZIP timer1:{{timer1}}
    h2 M {{m}}
    h2 M2 {{m2}}
    div
      el-button(v-on:click="handlerTestTime") TestTime
    div
      el-button(v-on:click="handlerZipCompressDir") ZipCompressDir
      el-button(v-on:click="handlerZipUncompress") ZipUncompress
    div
      button(v-on:click="createZip") 压
      br
      button(v-on:click="createUnZip") 解
      br
      button(v-on:click="autoDownload") 查
      br
      button(v-on:click="openMaterial") 开
      br
      button(v-on:click="startApp") 启动
</template>

<script type="text/ecmascript-6">
  // import zipper from 'zip-local'
  import fs from 'fs'
  import http from 'http'
  import url from 'url'
  import nodeCmd from 'node-cmd'
  import AdmZip from 'adm-zip'
  // import compressing from 'compressing'
  import {dateFormat} from '../config/utils'

  export default {
    data() {
      return {
        localMaterialFolder: this.$KalixGlobalConfig.LocalMaterialFolder,
        examMaterialFolder: this.$KalixGlobalConfig.ExamMaterialFolder,
        fileName: null,
        timer1: null,
        m: {},
        m2: {},
        mt: {}
      }
    },
    mounted() {
      // this.websocket()
      // this.autoDownload()
    },
    methods: {
      handlerTestTime() {
        this.mt = {}
        this.totalMinute = 0.1 * 60 // 考试总时长
        let examTime = `2019/03/06 14:01:30`
        let _time1 = (new Date(examTime)).getTime()
        let currentTime = (new Date()).getTime()
        if (_time1 > currentTime) {
          let tt = _time1 - currentTime
          this.timer1 = Math.floor(tt / 1000)
          if (this.timer1) {
            this.beginTime('a', () => {
              this.timer1 -= 1
              this.m = dateFormat(this.timer1)
              if (this.timer1 <= 0) {
                this.beginExam()
                clearInterval(this.mt['a'])
              }
            })
          }
        } else {
          console.log('已经开始考试')
        }
      },
      beginExam() {
        console.log('开始考试!计时开始！')
        this.beginTime('be', () => {
          this.totalMinute -= 1
          this.m2 = dateFormat(this.totalMinute)
          if (this.totalMinute <= 0) {
            console.log('结束！')
            clearInterval(this.mt['be'])
          }
        })
      },
      /**
       * 倒计时
       * @param callBack
       */
      beginTime(mtKey, callBack) {
        this.mt[mtKey] = setInterval(() => {
          callBack()
        }, 1000)
      },
      handlerZipCompressDir() {
        // compressing.zip.compressDir(`D:\\test4`, 'D:\\test\\4.zip')
        //   .then(() => {
        //     console.log('success')
        //   })
        //   .catch(err => {
        //     console.error(err)
        //   })
      },
      handlerZipUncompress() {
        // compressing.zip.uncompress(`D:\\test\\4.zip`, 'D:\\test3')
        //   .then(() => {
        //     console.log('success')
        //   })
        //   .catch(err => {
        //     console.error(err)
        //   })
      },
      startApp() {
        nodeCmd.get(`${this.materialFolder}demo.psd`)
      },
      async openMaterial() {
        this.fileName = `1.zip`
        let checkFolderFlag = await this._checkFolder(this.examMaterialFolder)
        if (!checkFolderFlag) {
          let createFolderFlag = await this._createFolder(this.examMaterialFolder)
          if (createFolderFlag) {
            this.decompressZip()
          }
        } else {
          this.decompressZip()
        }
      },
      decompressZip() {
        let keyIdx = this.fileName.lastIndexOf(`.`)
        let folderName = this.fileName.slice(0, keyIdx)
        let unzip = new AdmZip(this.localMaterialFolder + this.fileName)
        this.materialFolder = `${this.examMaterialFolder + folderName}/`
        unzip.extractAllTo(this.materialFolder, true)
        nodeCmd.get(`start ${this.materialFolder}`)
      },
      async autoDownload() {
        let checkFolderFlag = await this._checkFolder(this.localMaterialFolder)
        if (!checkFolderFlag) {
          let createFolderFlag = await this._createFolder(this.localMaterialFolder)
          if (createFolderFlag) {
            this._getMaterial()
          }
        } else {
          this._getMaterial()
        }
      },
      _createFolder(_folder) {
        return new Promise((resolve, reject) => {
          fs.mkdir(_folder, (err) => {
            err ? resolve(false) : resolve(true)
          })
        })
      },
      _checkFolder(_folder) {
        return new Promise((resolve, reject) => {
          fs.access(_folder, (err) => {
            err ? resolve(false) : resolve(true)
          })
        })
      },
      _getMaterial() {
        let urls = [
          'http://localhost:7780/material/1.zip',
          'http://localhost:7780/material/2.zip',
          'http://localhost:7780/material/3.zip',
          'http://localhost:7780/material/4.zip',
          'http://localhost:7780/material/5.zip',
          'http://localhost:7780/material/6.zip',
          'http://localhost:7780/material/7.zip'
        ]
        this.items = []
        urls.forEach(e => {
          let item = url.parse(e)
          let keyIndex = item.path.lastIndexOf('/')
          this.items.push({
            host: item.hostname,
            port: item.port,
            path: item.path,
            fileName: keyIndex > -1 ? item.path.slice(keyIndex + 1) : null
          })
        })
        this._de(0)
      },
      _end() {
        console.log('_end:')
      },
      _de(idx) {
        console.log('idx', idx)
        if (this.items.length && this.items[idx]) {
          this._downloadFile(this.items[idx], idx)
        } else {
          this._end()
        }
      },
      _downloadFile({host, port, path, fileName}, idx) {
        let options = {host, port, path}
        let file = fs.createWriteStream(this.localMaterialFolder + fileName)

        http.get(options, res => {
          res
            .on('data', data => {
              file.write(data)
            })
            .on('end', () => {
              file.end()
              console.log(fileName + ' downloaded to ' + this.localMaterialFolder)
              this._de(idx += 1)
            })
        })
      },
      createZip() {
        // zipper.zip(`d:\\exam\\3DMAX\\`).compress().save(`d:\\exam\\3DMAX\\target.zip`)
      },
      createUnZip() {
      },
      websocket() {
        if ('WebSocket' in window) {
          // let socketUrl = this.$KalixGlobalConfig.baseWsURL + '?loginname=' + this.$KalixCatch.get('loginname') + '&wsMessage=CommonMessage'
          let socketUrl = window.KalixConfig.baseWsURL + '?loginname=' + this.$KalixCatch.get('loginname') + '&wsMessage=CommonMessage'
          let ws = new WebSocket(socketUrl)
          ws.onopen = () => {
            // Web Socket 已连接上，使用 send() 方法发送数据
          }
          ws.onmessage = evt => {
            //  获取消息数量
            let data = JSON.parse(evt.data)
            if (data && data.msgCount) {
              this.msgCount = data.msgCount
            } else {
              this.msgCount = 0
            }
            //  获取最新消息
            if (data && data.msgTag && data.msgTag.length) {
              let msg = JSON.parse(data.msgTag)
              let headerNotif = this.$notify({
                title: msg.title,
                message: msg.content,
                type: 'success',
                duration: 10000,
                onClick: () => {
                  this.$router.push({path: `/common/receiver`})
                  headerNotif.close()
                }
              })
            }
          }
          ws.onclose = function () {
            // 关闭 websocket
            console.log('连接已关闭...')
          }
          // 组件销毁时调用，中断websocket链接
          this.over = () => {
            ws.close()
          }
        } else {
          this.$KalixMessage.info('您当前使用的浏览器不支持WebSocket，无法接收服务器消息！')
        }
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
</style>
